package com.elinkway.infinitemovies.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.elinkway.infinitemovies.adapter.AlbumGridViewAdapter;
import com.elinkway.infinitemovies.utils.AlbumHelper;
import com.elinkway.infinitemovies.utils.BitmapUtils;
import com.elinkway.infinitemovies.utils.ImageBucket;
import com.elinkway.infinitemovies.utils.ImageItem;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.PublicWay;
import com.le123.ysdq.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 这个是进入相册显示所有图片的界面
 *
 * @author king
 * @version 2014年10月18日  下午11:47:15
 * @QQ:595163260
 */
public class AlbumActivity extends BaseActionBarActivity {
    //显示手机里的所有图片的列表控件
    private GridView gridView;
    //当手机里没有图片时，提示用户没有图片的控件
    private TextView tv;
    //gridView的adapter
    private AlbumGridViewAdapter gridImageAdapter;
    //完成按钮
    private Button okButton;
    // 取消按钮
    private Button cancel;
    private Intent intent;
    private Context mContext;
    private ArrayList<ImageItem> dataList;
    private AlbumHelper helper;
    public static List<ImageBucket> contentList;
    public static Bitmap bitmap;
    private ActionBar mActionBar;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plugin_camera_album);
        mActionBar = getSupportActionBar();
        mActionBar.setTitle(getString(R.string.picture));
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE
                | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
        PublicWay.activityList.add(this);
        mContext = this;
        //注册一个广播，这个广播主要是用于在GalleryActivity进行预览时，防止当所有图片都删除完后，再回到该页面时被取消选中的图片仍处于选中状态
//		IntentFilter filter = new IntentFilter("data.broadcast.action");
//		registerReceiver(broadcastReceiver, filter);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.plugin_camera_no_pictures);
        init();
        initListener();
        //这个函数主要用来控制预览和完成按钮的状态
        isShowOkBt();
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            gridImageAdapter.notifyDataSetChanged();
        }
    };

    // 完成按钮的监听
    private class AlbumSendListener implements OnClickListener {
        public void onClick(View v) {
            overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
            BitmapUtils.copyImageItem(BitmapUtils.selectBitmap, BitmapUtils.tempSelectBitmap);
            setResult(RESULT_OK);
            finish();
        }

    }


    // 取消按钮的监听
    private class CancelListener implements OnClickListener {
        public void onClick(View v) {
            BitmapUtils.tempSelectBitmap.clear();
            gridImageAdapter.notifyDataSetChanged();
            isShowOkBt();
        }
    }


    // 初始化，给一些对象赋值
    private void init() {
        helper = AlbumHelper.getHelper();
        helper.init(getApplicationContext());

        contentList = helper.getImagesBucketList(true);
        dataList = new ArrayList<ImageItem>();
        for (int i = 0; i < contentList.size(); i++) {
            dataList.addAll(contentList.get(i).imageList);
        }
        Collections.sort(dataList, new FileComparator());
        cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new CancelListener());
        intent = getIntent();
        Bundle bundle = intent.getExtras();
        gridView = (GridView) findViewById(R.id.myGrid);
        LogUtils.e("", "AlbumGridViewAdapter " + BitmapUtils.tempSelectBitmap.size());
        gridImageAdapter = new AlbumGridViewAdapter(this, dataList,
                BitmapUtils.tempSelectBitmap);
        gridView.setAdapter(gridImageAdapter);
        tv = (TextView) findViewById(R.id.myText);
        gridView.setEmptyView(tv);
        okButton = (Button) findViewById(R.id.ok_button);
        okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size()
                + "/" + PublicWay.num + ")");
    }

    private void initListener() {

        gridImageAdapter
                .setOnItemClickListener(new AlbumGridViewAdapter.OnItemClickListener() {

                    @Override
                    public void onItemClick(final ToggleButton toggleButton,
                                            int position, boolean isChecked, Button chooseBt) {
                        if (BitmapUtils.tempSelectBitmap.size() >= PublicWay.num) {
                            toggleButton.setChecked(false);
                            chooseBt.setVisibility(View.GONE);
                            if (!removeOneData(dataList.get(position))) {
                                Toast.makeText(AlbumActivity.this, R.string.only_choose_num, Toast.LENGTH_SHORT).show();
                            }
                            return;
                        }
                        if (isChecked) {
                            chooseBt.setVisibility(View.VISIBLE);
                            BitmapUtils.tempSelectBitmap.add(dataList.get(position));
                            okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size()
                                    + "/" + PublicWay.num + ")");
                        } else {
                            BitmapUtils.tempSelectBitmap.remove(dataList.get(position));
                            chooseBt.setVisibility(View.GONE);
                            okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
                        }
                        isShowOkBt();
                    }
                });

        okButton.setOnClickListener(new AlbumSendListener());

    }

    private boolean removeOneData(ImageItem imageItem) {
        if (BitmapUtils.tempSelectBitmap.contains(imageItem)) {
            BitmapUtils.tempSelectBitmap.remove(imageItem);
            okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
            return true;
        }
        return false;
    }

    public void isShowOkBt() {
        if (BitmapUtils.tempSelectBitmap.size() > 0) {
            okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
            okButton.setPressed(true);
            okButton.setClickable(true);
            okButton.setTextColor(Color.WHITE);
        } else {
            okButton.setText(getString(R.string.done) + "(" + BitmapUtils.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
//            okButton.setPressed(false);
//            okButton.setClickable(false);
            okButton.setTextColor(Color.parseColor("#E1E0DE"));
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BitmapUtils.tempSelectBitmap.clear();
            finish();
        }
        return false;

    }

    @Override
    public void dealWithUmeng() {

    }

    @Override
    public void dealWithVisitUmeng() {

    }

    @Override
    protected void onRestart() {
        isShowOkBt();
        super.onRestart();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private class FileComparator implements Comparator<ImageItem> {

        @Override
        public int compare(ImageItem lhs, ImageItem rhs) {
            if(lhs.getBitFile().lastModified()<rhs.getBitFile().lastModified()){
                return 1;//最后修改的照片在前
            }else{
                return -1;
            }
        }

    }
}
